﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PlayBox
{
    public partial class Login : Form
    {
        public String Username
        {
            get
            {
                return txtUser.Text;
            }
            set
            {
                txtUser.Text = value;
                txtUser.ReadOnly = true;
                btnRegister.Visible = false;
                txtPassword.SelectAll();
                txtPassword.Focus();
            }
        }

        public Login()
        {
            InitializeComponent();
            chkAutoLogin.Checked = User.IsAutoLoggedIn;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            btnOk.Enabled = false;
            progressLogin.Visible = true;
            btnRegister.Enabled = false;

            var t = new System.Threading.Tasks.Task(() =>
            {
                User.LogIn(txtUser.Text, txtPassword.Text, chkAutoLogin.Checked);
                this.Invoke(new Action(LoginFinished));
            });
            t.Start();
        }

        private void LoginFinished ()
        {
            if (!User.IsLoggedIn)
            {
                MessageBox.Show("Benutzername oder Passwort falsch", "Fehler bei Login", MessageBoxButtons.OK);
                btnOk.Enabled = true;
                btnRegister.Enabled = true;
                progressLogin.Visible = false;
            }
            else
            {
                this.Close();
            }
        }

        private void txtUser_TextChanged(object sender, EventArgs e)
        {
            CheckValid();
        }

        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            CheckValid();
        }

        private void CheckValid ()
        {
            btnOk.Enabled = (!txtUser.Enabled || txtUser.TextLength > 0) && txtPassword.TextLength > 0;
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            var register = new Register();
            register.Username = txtUser.Text;
            register.ShowDialog();

            if (User.IsLoggedIn)
                this.Close();
        }
    }
}
